/**
 * date: 2010-08-30
 */
package com.epro.dx.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.epro.dx.R;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.model.AddressModel;
import com.weipu.common.facade.model.OrderModel.ShipAddress;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.GlobalConfig.UserSessionCfg;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Activity util
 *
 * @author hjd008
 * @version [版本号, 2015-1-7]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@SuppressLint("NewApi")
public final class ActivityUtil {
    private ActivityUtil() {
    }

    /**
     * 默认图片等级（243x243大小图片）
     */
    public static final String DEFAULT_ICON_GRADE_1 = "243x243";

    /**
     * 默认图片等级（488x488大小图片）
     */
    public static final String DEFAULT_ICON_GRADE_2 = "488x488";

    /**
     * 默认图片等级（1080x875大小图片）
     */
    public static final String DEFAULT_ICON_GRADE_3 = "1080x875";

    /**
     * 获取默认图片 243x243
     *
     * @return 默认图片
     */
    public static Bitmap getDefault243(Context context) {
        return BitmapFactory.decodeResource(context.getResources(),
                R.drawable.default243_243);
    }

    /**
     * 获取默认图片 488x488
     *
     * @return 默认图片
     */
    public static Bitmap getDefault488(Context context) {
        return BitmapFactory.decodeResource(context.getResources(),
                R.drawable.default488_488);
    }

    /**
     * 获取默认图片 1080x875
     *
     * @return 默认图片
     */
    public static Bitmap getDefault875(Context context) {
        return BitmapFactory.decodeResource(context.getResources(),
                R.drawable.default1080_875);
    }

    /**
     * 获得圆角图片的方法，
     *
     * @param bitmap
     * @param roundPx
     * @return Bitmap [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx,
                                                Context context) {
        Bitmap output = null;
        if (null != bitmap) {
            output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                    Config.ARGB_8888);
            Canvas canvas = new Canvas(output);

            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(rect);

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
        } else {
            output = BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.default488_488);
        }
        return output;
    }

    /**
     * 将Drawable转为Bitmap
     *
     * @param drawable
     * @return Bitmap [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static Bitmap drawableToBitmap(Drawable drawable, Context context) {
        Bitmap bitmap = null;
        if (null != drawable) {
            bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            // canvas.setBitmap(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
        } else {
            bitmap = BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.default488_488);
        }
        return bitmap;
    }

    /**
     * 缩放图片
     *
     * @param bitmap
     * @param w
     * @param h
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        float scaleWidth = ((float) w) / width;
        float scaleHeight = ((float) h) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    }

    /**
     * 判断是否登录
     *
     * @return boolean [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static boolean isLogin(Context context) {
        return TextUtils.equals("true", StringUtil.getConfig(context,
                ServerConstant.Parameter.PARAMETER_NAME_IS_LOGIN));
    }

    /**
     * 获取用户ID
     */
    public static Long getCustomerID() {
        String customerid = GlobalConfig.getInstance().getUserSessionCfg()
                .getCustomerid();
        if (null == customerid || "".equals(customerid)) {
            customerid = StringUtil.getConfig(
                    ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID, "0");
        }
        return Long.parseLong(customerid);
    }

    /**
     * 获取用户登录Token
     */
    public static String getCustomerToken() {
        UserSessionCfg userCfg = GlobalConfig.getInstance().getUserSessionCfg();
        String token = userCfg.getToken();
        if (null == token || "".equals(token)) {
            token = StringUtil.getConfig(
                    ServerConstant.Parameter.PARAMETER_NAME_TOKEN, "0");
            userCfg.setToken(token);
        }
        return token;
    }

    /**
     * 获取创建订单所需的ShipAddress
     *
     * @param addressModel
     * @return
     */
    public static ShipAddress getShipAddress(AddressModel addressModel) {
        ShipAddress shipAddress = new ShipAddress();
        if (null != addressModel) {
            AddressModel.Address address = addressModel.getAddress();
            if (null != address) {
                shipAddress.setFirstName(address.getFirstName());
                shipAddress.setLastName(address.getLastName());
                shipAddress.setCountry(addressModel.getCountryName());
                shipAddress.setState(address.getState());
                shipAddress.setCity(address.getCity());
                shipAddress.setStreet1(address.getStreet1());
                shipAddress.setStreet2(address.getStreet2());
                shipAddress.setPostalCode(address.getPostalCode());
                shipAddress.setPhone(address.getMobilePhone());
                shipAddress.setPhoneNumber(address.getPhoneNumber());
                // 由于在创建订单接口中Mobile代表是必填项 所以要与收获地址做匹配
                shipAddress.setMobile(address.getPhoneNumber());
                shipAddress.setEmail(address.getEmail());
                // shipAddress.setMobile("52052052");
                // shipAddress.setEmail("1774286097@qq.com");
                return shipAddress;
            }
        }
        return null;
    }

    /**
     * 获取相应卡图标
     *
     * @param cardType 卡类型
     * @return
     */
    public static int getCardTypeResId(String cardType) {
        int resId = R.drawable.msater_card_icon;
        if ("MasterCard".equals(cardType)) {
            resId = R.drawable.msater_card_icon;
        } else if ("VISA".equals(cardType)) {
            resId = R.drawable.visa_icon;
        } else if ("AmericanExpress".equals(cardType)) {
            resId = R.drawable.american_express_icon;
        } else if ("DinersClub".equals(cardType)) {
            resId = R.drawable.diners_club_icon;
        } else if ("Discover".equals(cardType)) {
            resId = R.drawable.discover_icon;
        } else if ("JCB".equals(cardType)) {
            resId = R.drawable.jcb_icon;
        }
        return resId;
    }

    /**
     * 创建0-10随机数
     *
     * @return
     */
    public static int[] getRandomNum() {
        Random random = new Random();
        int[] data = new int[10];
        boolean b;
        boolean b2 = false;
        boolean b3 = true;
        int x;
        for (int i = 0; i < 10; i++) {
            b = true;
            while (b) {
                x = random.nextInt(10);
                if (x == 0 && b3) {
                    b3 = false;
                    b = false;
                }
                for (int y : data) {
                    if (x == y) {
                        b2 = false;
                        break;
                    } else {
                        b2 = true;
                    }
                }
                if (b2) {
                    data[i] = x;
                    b = false;
                    break;
                }
            }

        }
        return data;
    }

    /**
     * 初始化键盘控件及基本设置
     *
     * @param keyboardView
     * @param editText
     */
    public static void intKeyboradView(final View keyboardView,
                                       final EditText editText) {

        final Editable editable = editText.getEditableText();
        final Button btn0 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn0);
        final Button btn1 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn1);
        final Button btn2 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn2);
        final Button btn3 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn3);
        final Button btn4 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn4);
        final Button btn5 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn5);
        final Button btn6 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn6);
        final Button btn7 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn7);
        final Button btn8 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn8);
        final Button btn9 = (Button) keyboardView
                .findViewById(R.id.keyboard_btn9);
        final Button btn_del = (Button) keyboardView
                .findViewById(R.id.keyboard_btn_del);

        btn0.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn0.getText().toString();
                editable.insert(index, str);
            }
        });
        btn1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn1.getText().toString();
                editable.insert(index, str);
            }
        });
        btn2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn2.getText().toString();
                editable.insert(index, str);
            }
        });
        btn3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn3.getText().toString();
                editable.insert(index, str);
            }
        });
        btn4.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn4.getText().toString();
                editable.insert(index, str);
            }
        });
        btn5.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn5.getText().toString();
                editable.insert(index, str);
            }
        });
        btn6.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn6.getText().toString();
                editable.insert(index, str);
            }
        });
        btn7.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn7.getText().toString();
                editable.insert(index, str);
            }
        });
        btn8.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn8.getText().toString();
                editable.insert(index, str);
            }
        });
        btn9.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int index = editText.getSelectionStart();
                String str = btn9.getText().toString();
                editable.insert(index, str);
            }
        });

        btn_del.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try {
                    int index = editText.getSelectionStart();
                    editable.delete(index - 1, index);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        btn_del.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View arg0) {
                editText.setText("");
                return false;
            }
        });
        int[] randomNum = ActivityUtil.getRandomNum();
        btn0.setText(randomNum[0] + "");
        btn1.setText(randomNum[1] + "");
        btn2.setText(randomNum[2] + "");
        btn3.setText(randomNum[3] + "");
        btn4.setText(randomNum[4] + "");
        btn5.setText(randomNum[5] + "");
        btn6.setText(randomNum[6] + "");
        btn7.setText(randomNum[7] + "");
        btn8.setText(randomNum[8] + "");
        btn9.setText(randomNum[9] + "");
    }

    /**
     * 获取屏幕宽高
     *
     * @param context Activity类型Context
     * @return
     */
    public static Point getScreenSize(Activity context) {
        WindowManager windowManager = context.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int screenHeight = display.getHeight();
        Point point = new Point();
        point.set(screenWidth, screenHeight);
        return point;
    }

    /**
     * @param activity 要设置的页面Activity
     * @param color    颜色值－－为0设置为透明状态栏
     * @param rootView 为了应对首页的4个Fragment，其他地方传null即可
     * @创建：Tony 2016-5-25下午4:31:29
     * @描述：设置状态栏颜色
     */
    public static void setStatusColor(Activity activity, int color, View rootView) {
        View status = null;
        if (null != rootView) {
            status = rootView.findViewById(R.id.my_status);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (null != status) {
                status.setVisibility(View.VISIBLE);
            }
            if (color == 0) {
                activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            } else {
//				activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                activity.getWindow().setStatusBarColor(color);
            }
        } else {
            if (null != status) {
                status.setVisibility(View.GONE);
            }
        }
    }

    public static void setTranslucentState(Activity activity) {
        //以上代码基本解决适配各种版本全透明状态栏（如导航栏有需求可以再加导航栏） ，且状态栏的颜色会随着Toolbar的颜色改变而改变
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //这个属性4.4算是全透明（有的机子是过渡形式的透明），5.0就是半透明了 我的模拟器、真机都是半透明，
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4 全透明状态栏
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0 全透明实现
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);//calculateStatusColor(Color.WHITE, (int) alphaValue)
        }
    }

    /**
     * 判断是不是锁屏状态
     *
     * @param context 上下文
     * @return true:锁屏 false：解锁
     */
    public static boolean isLock(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();//如果为true，则表示屏幕“亮”了，否则屏幕“暗”了。
//        KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
//        boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
        return !isScreenOn;
    }

    /**
     * 权限:<uses-permission android:name="android.permission.GET_TASKS"/>
     * 判断当前界面是否是桌面 ,先获取桌面应用的程序包名,然后判断当前显示活动包名是否包含在内
     */
    public static boolean isHome(Context context) {
//		ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
//		List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
//		List<String> strs = getHomes(context);
//		if(strs != null && strs.size() > 0){
//			return strs.contains(rti.get(0).topActivity.getPackageName());
//		}else{
//			return false;
//		}

        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        return getHomes(context).contains(rti.get(0).topActivity.getPackageName());
    }

    /**
     * 获得属于桌面的应用的应用包名称
     *
     * @return 返回包含所有桌面应用的包名的字符串列表
     */
    public static List<String> getHomes(Context context) {
        List<String> names = new ArrayList<String>();
        PackageManager packageManager = context.getPackageManager();
        //属性
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo ri : resolveInfo) {
            names.add(ri.activityInfo.packageName);
            Logger.e("zlw", "属于桌面的应用有: " + ri.activityInfo.packageName);
        }
        return names;
    }

    /**
     * 检查是否有悬浮窗权限
     *
     * @param context
     */
    public static boolean checkNotiPermission(final Context context) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(context)) {

//				AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("设置权限")
//						.setMessage("需要开启悬浮窗权限,是否马上去开启？")
//						.setNegativeButton("不开启", new DialogInterface.OnClickListener() {
//							@Override
//							public void onClick(DialogInterface dialog, int which) {
//								dialog.dismiss();
//							}
//						})
//						.setPositiveButton("开启", new DialogInterface.OnClickListener() {
//							@Override
//							public void onClick(DialogInterface dialog, int which) {
//								dialog.dismiss();
//
//							}
//						});
//
//				builder.show();
                return false;
            }
            return true;
        }
        return false;
    }

    public static float getStatusHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
